package com.shouhuobao.take.identity;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.app.camera.CameraManager;
import com.iseastar.BaseActivity2;
import com.iseastar.guojiang.consts.AppConfig;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.ReqResult;
import com.shouhuobao.station.R;

import java.io.FileNotFoundException;
import java.util.regex.Pattern;

import droid.frame.utils.http.BitmapUtils;
import droid.frame.utils.lang.Str;

/**
 * 身份证验证主界面
 *
 * @author joker
 */
public class AuthenticationActivity extends BaseActivity2 implements View.OnClickListener {

    private static final int FRONT = 1;//正面身份证
    private static final int INHAND = 2;//手持身份证

    EditText mUserNameET;
    EditText mIdentityNumberET;
    LinearLayout mFrontLL;//正面身份证整体布局
    ImageView mFrontIV;//正面身份证照片
    LinearLayout mUnChooseFrontIdentityLL;//未选择正面身份证之前的布局
    LinearLayout mInHandLL;//手持身份证整体布局
    ImageView mInHandIV;//手持身份证照片
    LinearLayout mUnChooseInHandIdentityLL;//未选择手持身份证照片之前的布局
    TextView mSureTV;//提交照片的确认按钮

    Dialog centerDialog = null;
    CameraManager mCameraManager = null;//照相机管理类

    int mFrontOrInHand = 0;//判断是正面照片还是手持身份证的  1正面身份证 2 手持身份证
    String forntImagePath = "";//正面身份证图片的地址
    String inHandImagePath = "";//手持身份证的地址
    String[] resultImagePath = new String[2];//存放服务器返回图片的地址

    private int isFrom;//判断是否需要有返回数据  0已经认证，进行修改  1未认证过
    private boolean isSuccess = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.activity_identity_authentication);
        super.findViewById();
        getAppTitle().setCommonTitle("身份认证");
        mCameraManager = CameraManager.getInstance();
        mUserNameET = (EditText) findViewById(R.id.usernameET);
        mIdentityNumberET = (EditText) findViewById(R.id.identitynumberET);
        mFrontLL = (LinearLayout) findViewById(R.id.frontLL);
        mFrontIV = (ImageView) findViewById(R.id.frontIV);
        mUnChooseFrontIdentityLL = (LinearLayout) findViewById(R.id.unchoosefrontidentityLL);
        mInHandLL = (LinearLayout) findViewById(R.id.inhandLL);
        mInHandIV = (ImageView) findViewById(R.id.inhandIV);
        mUnChooseInHandIdentityLL = (LinearLayout) findViewById(R.id.unchooseinhandidentityLL);
        mSureTV = (TextView) findViewById(R.id.sureTV);
        mFrontLL.setOnClickListener(this);
        mInHandLL.setOnClickListener(this);
        mSureTV.setOnClickListener(this);

        isFrom = getIntent().getIntExtra("isFrom", 0);
        if (isFrom == 0) {
            String idName = getIntent().getStringExtra("idName");
            String idCard = getIntent().getStringExtra("idCard");
            mUserNameET.setText(idName);
            mUserNameET.setSelection(idName.length());
            mIdentityNumberET.setText(idCard);
            mIdentityNumberET.setSelection(idCard.length());
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.frontLL://选择正面身份证
                new SelectPhoto(selectCenterDialog(this, R.layout.dialog_identity_choose), 0);
                break;
            case R.id.inhandLL://选择手持身份证
                new SelectPhoto(selectCenterDialog(this, R.layout.dialog_identity_choose), 1);
                break;
            case R.id.sureTV://确认提交按钮
                //如果两个都隐藏，说明已经选好了两张图片，这个时候才可以提交上传
                if (mUnChooseFrontIdentityLL.getVisibility() == View.GONE && mUnChooseInHandIdentityLL.getVisibility() == View.GONE) {
                    if ("".equals(mUserNameET.getText().toString().trim())) {
                        showToast("请输入真实姓名");
                    } else if ("".equals(mIdentityNumberET.getText().toString()) || !Str.isIdentityNumber(mIdentityNumberET.getText().toString())) {
                        showToast("请输入正确的身份证号");
                    } else {
                        if (!isEmpty(forntImagePath) && !isEmpty(inHandImagePath)) {
                            showLoadingDialog("正在上传");
                            String[] images = new String[]{forntImagePath, inHandImagePath};
                            AppHttp.getInstance().postFils(images);
                        }
                    }
                } else {
                    showToast("请选择证件进行上传");
                }
                break;
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        ReqResult<String> result = JSON.parser(msg.obj, String.class);
        switch (msg.what) {
            //上传审核信息
            case MsgID.identity_info:
                cancelLoadingDialog();
                if (checkLoginStatus(result)) {
                    isSuccess = true;
                    AuthenticationActivity.this.finish();
                } else {
                    showToast(result.getMessage());
                }
                break;
            //上传图片
            case MsgID.upload_image:
                if (checkLoginStatus(result)) {
                    if (result.getResult() == null) {
                        cancelLoadingDialog();
                        showToast("图片上传失败");
                        return true;
                    }
                    String path = result.getResult().replace("\\", "").replace("[", "").replace("]", "").replace("\"", "");
                    resultImagePath = path.split(",");
                    if (resultImagePath == null || resultImagePath.length == 0) {
                        cancelLoadingDialog();
                        showToast("图片上传失败");
                        return true;
                    }
                    AppHttp.getInstance().upLoadIdentityInfo(mUserNameET.getText().toString(), mIdentityNumberET.getText().toString(),
                            resultImagePath[0], resultImagePath[1]);
                } else {
                    cancelLoadingDialog();
                    showToast(result.getMessage());
                }
                break;
        }
        return super.handleMessage(msg);
    }

    /**
     * 弹出自定义对话框的相关展示操作类
     */
    class SelectPhoto implements View.OnClickListener {
        private int type;//区分是选择正面身份证的还是手持身份证，0正面 1手持身份证
        private ImageView bitmapinhandIV;//手持身份证
        private ImageView frontbitmap;//正面身份证

        public SelectPhoto(View view, int type) {
            this.type = type;
            bitmapinhandIV = (ImageView) view.findViewById(R.id.bitmapinhandIV);
            frontbitmap = (ImageView) view.findViewById(R.id.frontbitmap);
            view.findViewById(R.id.caremaBT).setOnClickListener(this);
            view.findViewById(R.id.localphotoBT).setOnClickListener(this);
            initdata();
        }

        private void initdata() {
            if (type == 0) {//正面
                frontbitmap.setVisibility(View.VISIBLE);
                bitmapinhandIV.setVisibility(View.GONE);
                mFrontOrInHand = FRONT;
            } else {
                frontbitmap.setVisibility(View.GONE);
                bitmapinhandIV.setVisibility(View.VISIBLE);
                mFrontOrInHand = INHAND;
            }
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.caremaBT:
                    Intent intent = new Intent();
                    intent.setClass(getContext(), IdentityCameraActivity.class);
                    intent.putExtra("type", "1");
                    startActivityForResult(intent, 102);
                    dissmissCenterDialog();
                    break;
                case R.id.localphotoBT:
                    mCameraManager.localPhoto(AuthenticationActivity.this);
                    dissmissCenterDialog();
                    break;
            }
        }
    }

    /**
     * 大图片保存路径
     */
    String tempUri = "file:///sdcard/temp.jpg";

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (CameraManager.ICameraRequestCode.CAMERA_PHOTO_LOCAL == requestCode) {
            if (data != null) {
                Uri uri = data.getData();
                if (uri != null) {
                    CameraManager.getInstance().cuttingWithXY(this, uri.toString(), tempUri, 5, 3);
                }
            }
        } else if (CameraManager.ICameraRequestCode.CAMERA_PHOTO_CUTTING == requestCode) {
            Bundle extras = data.getExtras();
            Uri imageUri = Uri.parse(tempUri);
            if (imageUri != null) {
                Bitmap bitmap = decodeUriAsBitmap(imageUri);
                if (bitmap != null) {
                    setIdentityImage(bitmap);
                }
            }
            if (extras != null) {
                Bitmap bitmap = extras.getParcelable("data");
                if (bitmap != null) {
                    setIdentityImage(bitmap);
                }
            }
        } else if (requestCode == 102) {//拍照返回的图片路径
            String capturePath = data.getStringExtra("file");
            Bitmap bitmap = BitmapUtils.loadBitmapFromLocal(capturePath);
            setIdentityImage(bitmap);
        }
    }

    private void setIdentityImage(Bitmap bitmap) {
        if (bitmap != null) {
            if (mFrontOrInHand == FRONT) {
                mUnChooseFrontIdentityLL.setVisibility(View.GONE);
                mFrontIV.setVisibility(View.VISIBLE);
                mFrontIV.setImageBitmap(bitmap);
                mFrontIV.setScaleType(ImageView.ScaleType.FIT_XY);
                forntImagePath = BitmapUtils.cacheBitmapToFile(bitmap, AppConfig.getCacheDir() + "/" + System.currentTimeMillis() + ".jpg");
            } else {
                mUnChooseInHandIdentityLL.setVisibility(View.GONE);
                mInHandIV.setVisibility(View.VISIBLE);
                mInHandIV.setImageBitmap(bitmap);
                mInHandIV.setScaleType(ImageView.ScaleType.FIT_XY);
                inHandImagePath = BitmapUtils.cacheBitmapToFile(bitmap, AppConfig.getCacheDir() + "/" + System.currentTimeMillis() + ".jpg");
            }
            checkSureButtonState();
        }
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void checkSureButtonState() {
        if (mUnChooseFrontIdentityLL.getVisibility() == View.GONE && mUnChooseInHandIdentityLL.getVisibility() == View.GONE) {
            mSureTV.setEnabled(true);
        }
    }

    /**
     * 根据图片Url，返回Bitmap
     *
     * @param uri
     * @return
     */
    private Bitmap decodeUriAsBitmap(Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }

    /**
     * 中间显示的对话框
     *
     * @param activity
     * @param resource
     * @return
     */
    public View selectCenterDialog(Activity activity, int resource) {
        centerDialog = new Dialog(activity, R.style.dialog_no_translucent);
        Window window = centerDialog.getWindow();
        android.view.WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        //        params.alpha = 0.3f;
        window.setGravity(Gravity.CENTER);
        window.setAttributes(params);// 设置生效

        LayoutInflater fac = LayoutInflater.from(activity);
        View more_pop_menu = fac.inflate(resource,
                null);
        centerDialog.setCanceledOnTouchOutside(true);
        centerDialog.setContentView(more_pop_menu);
        params.height = android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
        params.width = (int) (activity.getWindowManager().getDefaultDisplay()
                .getWidth() * 0.8);
        centerDialog.show();
        return more_pop_menu;
    }

    public void dissmissCenterDialog() {
        try {
            if (centerDialog != null) {
                centerDialog.dismiss();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void finish() {
        Intent intent = new Intent();
        if (isFrom == 1 && isSuccess) {//如果最新认证，并且上传成功
            intent.putExtra("success", 0);
            intent.putExtra("idName", mUserNameET.getText().toString().trim());
            intent.putExtra("idCard", mIdentityNumberET.getText().toString().trim());
        } else if (isFrom == 1 && !isSuccess) {//最新认证，上传失败
            intent.putExtra("success", 1);
        } else {//修改
            if (isSuccess) {//修改成功
                intent.putExtra("success", 0);
                intent.putExtra("idName", mUserNameET.getText().toString().trim());
                intent.putExtra("idCard", mIdentityNumberET.getText().toString().trim());
            } else {//修改失败
                intent.putExtra("success", 1);
            }
        }
        setResult(Activity.RESULT_OK, intent);
        super.finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }
}